package com.flyco.modules.system.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.flyco.common.exception.FlycoException;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.stm.mapper.StmStoreInfoMapper;
import com.flyco.modules.system.entity.SysMsgNotice;
import com.flyco.modules.system.entity.SysMsgNoticeRecord;
import com.flyco.modules.system.mapper.SysMsgNoticeMapper;
import com.flyco.modules.system.mapper.SysMsgNoticeRecordMapper;
import com.flyco.modules.system.mapper.SysPermissionMapper;
import com.flyco.modules.system.model.StoreInfoModel;
import com.flyco.modules.system.service.ISysMsgNoticeService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 消息通知
 * @Author: flyco
 * @Date: 2024-06-19
 * @Version: V1.0
 */
@Service
public class SysMsgNoticeServiceImpl extends ServiceImpl<SysMsgNoticeMapper, SysMsgNotice> implements ISysMsgNoticeService {

    @Resource
    private SysMsgNoticeMapper sysMsgNoticeMapper;
    @Resource
    private SysMsgNoticeRecordMapper sysMsgNoticeRecordMapper;
    @Resource
    private StmStoreInfoMapper stmStoreInfoMapper;

    @Override
    public SysMsgNotice getWithRecordById(Long id) {
        SysMsgNotice notice = getById(id);
        List<SysMsgNoticeRecord> recordList = sysMsgNoticeRecordMapper.selectList(new QueryWrapper<SysMsgNoticeRecord>().eq("notice_id", id));
        if (recordList != null && !recordList.isEmpty()) {
            List<String> storeIds = recordList.stream().map(x -> x.getStoreId()).collect(Collectors.toList());
            List<StmStoreInfo> storeInfoList = stmStoreInfoMapper.selectList(new QueryWrapper<StmStoreInfo>().in("store_id", storeIds));
            if (storeInfoList != null && !storeInfoList.isEmpty()) {
                recordList.forEach(t -> {
                    StmStoreInfo model = storeInfoList.stream().filter(x -> x.getStoreId().toString().equals(t.getStoreId())).collect(Collectors.toList()).get(0);
                    if (model != null) {
                        t.setStoreCode(model.getCompanyCode().toString());
                        t.setChannelName(model.getChannelName());
                        t.setChannelId(model.getChannelId());
                        t.setStoreName(model.getName());
                    }
                });
            }
            notice.setNoticeRecordList(recordList);
        }
        return notice;
    }

    @Override
    public void saveWithRecord(SysMsgNotice sysMsgNotice) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        sysMsgNotice.setMsgStatus(0);
        sysMsgNotice.setMsgType(0);
        sysMsgNotice.setCreateBy(sysUser.getUsername());
        sysMsgNotice.setCreateTime(new Date());
        sysMsgNoticeMapper.insert(sysMsgNotice);
        if (sysMsgNotice.getNoticeRecordList() != null && !sysMsgNotice.getNoticeRecordList().isEmpty()) {
            sysMsgNotice.getNoticeRecordList().forEach(x -> {
                x.setNoticeId(sysMsgNotice.getId());
                x.setMsgTitle(sysMsgNotice.getMsgTitle());
                x.setCreateTime(new Date());
                x.setDeleteStatus(1);//新增默认没有任何不让看见
                x.setViewedStatus(0);
                sysMsgNoticeRecordMapper.insert(x);
            });
        }
    }

    @Override
    public void editWithRecord(SysMsgNotice sysMsgNotice) {
        SysMsgNotice notice = sysMsgNoticeMapper.selectById(sysMsgNotice.getId());
        notice.setMsgTitle(sysMsgNotice.getMsgTitle());
        notice.setMsgContent(sysMsgNotice.getMsgContent());
        notice.setMsgStatus(sysMsgNotice.getMsgStatus());
        notice.setAttachmentName(sysMsgNotice.getAttachmentName());
        notice.setAttachmentUrl(sysMsgNotice.getAttachmentUrl());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysMsgNotice.getMsgStatus() != null && sysMsgNotice.getMsgStatus() == 1)//审核通过
        {
            notice.setAuditBy(sysUser.getUsername());
            notice.setAuditTime(new Date());
        }
        notice.setUpdateBy(sysUser.getUsername());
        notice.setUpdateTime(new Date());
        sysMsgNoticeMapper.updateById(notice);
        if (!sysMsgNotice.getNoticeRecordList().isEmpty()) {
            List<SysMsgNoticeRecord> existsRecordList = sysMsgNoticeRecordMapper.selectList(new QueryWrapper<SysMsgNoticeRecord>().eq("notice_id", sysMsgNotice.getId()));
            List<SysMsgNoticeRecord> viewedList = existsRecordList.stream().filter(v -> v.getViewedStatus() == 1).collect(Collectors.toList());
            if (existsRecordList != null || !existsRecordList.isEmpty()) {//原通知明细表没有记录
                //先删除原有记录
                sysMsgNoticeRecordMapper.delete(new QueryWrapper<SysMsgNoticeRecord>().eq("notice_id", sysMsgNotice.getId()));
            }
            sysMsgNotice.getNoticeRecordList().forEach(x -> {
                x.setNoticeId(sysMsgNotice.getId());
                x.setMsgTitle(sysMsgNotice.getMsgTitle());
                x.setViewedStatus(0);
                x.setCreateTime(new Date());
                Integer deleteStatus = sysMsgNotice.getMsgStatus() != null && sysMsgNotice.getMsgStatus() == 1 ? 0 : 1;
                List<SysMsgNoticeRecord> tempList = viewedList.stream().filter(v -> v.getNoticeId() == x.getNoticeId() && x.getStoreId() == x.getStoreId()).collect(Collectors.toList());
                if (tempList != null && !tempList.isEmpty()) {
                    tempList.forEach(t -> {
                        if (t.getStoreId().equals(x.getStoreId()) && t.getNoticeId().equals(x.getNoticeId())) {
                            x.setViewedStatus(1);//原有经销商已经查看的
                        }
                    });
                }
                x.setDeleteStatus(deleteStatus);//新增默认没有任何不让看见
                sysMsgNoticeRecordMapper.insert(x);
            });
        } else {
            deleteMsgNoticeRecord(sysMsgNotice.getId(), 2);
        }
    }

    @Override
    public void deleteWithRecord(Long id) {
        SysMsgNotice notice = sysMsgNoticeMapper.selectById(id);
        if (notice != null) {
            if (notice.getDeleteStatus() == 1) {
                throw new FlycoException("当前消息已经删除，无需重复操作！");
            }
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        notice.setUpdateBy(sysUser.getUsername());
        notice.setUpdateTime(new Date());
        notice.setMsgStatus(0);
        notice.setDeleteStatus(1);
        sysMsgNoticeMapper.updateById(notice);
        deleteMsgNoticeRecord(id, 1);
    }

    @Override
    public void unAudit(Long id) {
        SysMsgNotice notice = sysMsgNoticeMapper.selectById(id);
        if (notice != null) {
            if (notice.getMsgStatus() != null && notice.getMsgStatus() == 0) {
                throw new FlycoException("当前消息已经撤销，无需重复操作！");
            }
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        notice.setUpdateBy(sysUser.getUsername());
        notice.setUpdateTime(new Date());
        notice.setMsgStatus(0);

        sysMsgNoticeMapper.updateById(notice);
        sysMsgNoticeMapper.unAudit(id);
        deleteMsgNoticeRecord(id, 2);
    }

    @Override
    public List<StoreInfoModel> getStoreByChannel(String channelIds) {
        QueryWrapper<StmStoreInfo> query = new QueryWrapper<>();
        query.eq("status", 9);
        if (StringUtils.isNotEmpty(channelIds)) {
            String[] channelIdList = channelIds.trim().split(",");
            query.in("channel_id", channelIdList);
        }
        List<StoreInfoModel> storeModelList = new ArrayList<>();
        List<StmStoreInfo> storeInfoList = stmStoreInfoMapper.selectList(query);
        if (!storeInfoList.isEmpty()) {
            storeInfoList.forEach(x -> {
                StoreInfoModel model = new StoreInfoModel();
                model.setChannelId(x.getChannelId());
                model.setChannelName(x.getChannelName());
                model.setStoreId(x.getStoreId().toString());
                model.setStoreName(x.getName());
                model.setStoreCode(x.getCompanyCode().toString());
                storeModelList.add(model);
            });
        }
        return storeModelList;
    }

    /**
     * 根据消息通知ID删除经销商查看关系表数据
     */
    private void deleteMsgNoticeRecord(Long noticeId, Integer type) {
        List<SysMsgNoticeRecord> recordList = sysMsgNoticeRecordMapper.selectList(new QueryWrapper<SysMsgNoticeRecord>().eq("notice_id", noticeId));
        if (recordList != null && !recordList.isEmpty()) {
            recordList.forEach(x -> {
                if (type == 1) {//通知删除
                    x.setDeleteStatus(1);
                } else {//通知撤销
                    if (x.getViewedStatus() != 1) {
                        x.setDeleteStatus(1);
                    }
                }
                sysMsgNoticeRecordMapper.updateById(x);
            });
        }
    }
}
